<template>
  <div class="app-container" id="container">
    <el-container>
      <el-aside style="width: 800px;height: 500px;background: white;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);">
      <el-row>
        <el-col :span="24">
          <div id="head">
            <el-tag type="info" class="head">
          <el-button  type="text" size="medium" @click="drugTableOpenAndClose" icon="el-icon-circle-plus">新增处方
          </el-button>
          <el-button type="text" :disabled="multiple" @click="handleDelete" icon="el-icon-remove"
                     v-hasPermi="['dms:herbal_prescription_record:addtoredis']">删除处方
          </el-button>
          <el-button type="text"  :disabled="multiple" @click="handleAdd" icon="el-icon-success"
                     v-hasPermi="['dms:herbal_prescription_record:addtodatabase']">开立处方</el-button>
          <el-button type="text" :disabled="multiple" @click="handleInvalid" icon="el-icon-error"
                     v-hasPermi="['dms:herbal_prescription_record:invalidate']">作废处方</el-button>
          <el-button type="text" @click="getHerbalPre()" icon="el-icon-refresh"
                     v-hasPermi="['dms:herbal_prescription_record:addtoredis']">刷新</el-button>
              <el-button :icon="elIfShow ? 'el-icon-caret-right' : 'el-icon-caret-left'" @click="showOrHidden" plain
                         class="btn_right">快捷操作</el-button>
<!--          <el-button @click="showOrHidden" plain  class="btn_right" :class=" !elIfShow ? 'el-icon-caret-right' : 'el-icon-caret-left' ">快捷操作</el-button>-->
            </el-tag>
          </div>
        <el-table :data="this.tableData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center"/>
          <el-table-column v-if="false" align="center" label="处方id" prop="id"/>
          <el-table-column align="center" label="处方名称" prop="name"/>
          <el-table-column align="center" label="总金额(元)" prop="amount">
            <template  slot-scope="scope">
              {{ scope.row.amount| rounding}} 元
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" prop="status">
            <template  slot-scope="scope">
              <el-button  >{{formatStatus[scope.row.status]}}</el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.status==-1" @click="editPrescription(scope.row)"  >编辑</el-button>
              <el-button type="text" v-else @click="viewPrescription(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      </el-row>
      </el-aside>
      <el-main style="border-left: #1c84c6">
        <transition name="el-fade-in-linear">
      <el-row  v-if="this.elIfShow" class="transition-box">
       <el-col :span="8" style=" width: 200px;margin-left: 10px">
         <el-button @click="getMedicineModelList" id="alone" type="text" >
           草药模板
         </el-button>
         <hr/>
         <el-table :data="this.modelList" @row-dblclick="handleDblClick" @row-click="handleClick">
           <el-table-column v-if="false" align="center" label="模板id" prop="id"/>
           <el-table-column align="center" label="模板名" prop="name"/>
           <el-table-column align="center" label="目的" prop="aim"/>
         </el-table>
         <div v-if="testModelShow">
           <el-row>
             <el-tag>模版详情</el-tag>
           </el-row>
           <el-row>
             <el-input v-model="this.modelInfo.name" disabled="disabled">
               <template slot="prepend" style="width: 30px">名称:</template>
             </el-input>
           </el-row>
           <el-row>
             <el-input v-model="this.modelInfo.code" disabled="disabled">
               <template slot="prepend">编码:</template>
             </el-input>
           </el-row>
           <el-row>
             <el-input v-model="this.modelInfo.aim" disabled="disabled">
               <template slot="prepend">简介:</template>
             </el-input>
           </el-row>
         </div>
       </el-col>

  </el-row>
  </transition>
  </el-main>
  </el-container>
    <!-- 添加处置项目弹窗 -->
   <el-dialog :title="title" :visible.sync="open"  class="dialog" @close="resetForm('herbalPrescription')" style="width: 2200px"  append-to-body>
     <el-container>
      <el-aside v-if="!showButton">
      <el-row>
        <!--药品数据-->
        <el-col :span="8" :xs="24">
          <!--查询常用草药品-->
          <div class="head-container" style="width: 250px" >
            <el-table v-loading="loading" :data="frequentDrugList" @row-click="drugClick"style="width:230px; overflow:auto;">
              <el-table-column label="ID" align="center" prop="drugId" v-if="false"/>
              <el-table-column label="药品名" align="center" prop="name" />
              <el-table-column label="价格(元)" align="center" prop="price" />
            </el-table>
          </div>
          <!--查询所有草药品-->
            <el-input
              v-model="drugName"
              placeholder="请输入药品名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 5px;width: 230px;"
              @blur="getDrugByName()"
            />
          <div class="head-container" style="width: 250px">
            <el-table v-loading="loading" :data="drugList" @row-click="drugClick"style="
           width:230px; max-height: 700px;overflow: auto;">
              <el-table-column label="ID" align="center" prop="drugId" v-if="false"/>
              <el-table-column label="药品名" align="center" prop="name" />
              <el-table-column label="价格(元)" align="center" prop="price" />
            </el-table>
            <pagination
            small
            :total="total"
            layout="prev, pager, next"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getDrugList"
          />
          </div>
        </el-col>
      </el-row>
      </el-aside>
     <el-main>
       <el-form ref="herbalPrescription" :disabled="showButton" :model="herbalPrescription" :rules="rules"  label-width="80px" size="mini">
         <el-row>
           <el-col :span="7">
             <el-form-item v-if="herbalPrescription.status!=-1"  label="处方名" prop="name">
               <el-input  v-model="herbalPrescription.name" ></el-input>
             </el-form-item>
             <el-form-item v-else label="处方名" >
               <el-input disabled  v-model="herbalPrescription.name" ></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="7">
             <el-form-item label="嘱托" prop="medicalAdvice">
               <el-input v-model="herbalPrescription.medicalAdvice" ></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="7">
             <el-form-item label="治法" prop="therapy">
               <el-input v-model="herbalPrescription.therapy" ></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="2 ">
             <el-button v-if="herbalPrescription.status==-1" style="margin-top: -5px;margin-left: 5px" @click="submitForm" v-hasPermi="['dms:herbal_prescription_record:edit']">保存处方</el-button>
               <el-button v-else style="margin-top: -5px;margin-left: 5px" @click="submitForm" v-hasPermi="['dms:herbal_prescription_record:addtoredis']" >添加处方</el-button>
           </el-col>
         </el-row>
         <el-row>
           <el-col :span="7">
             <el-form-item label="用法" prop="usageMeans">
               <el-select placeholder="请选择使用方法" size="small" v-model="herbalPrescription.usageMeans">
                 <el-option
                   :key="dict.dictValue"
                   :label="dict.dictLabel"
                   :value="parseInt(dict.dictValue)"
                   v-for="dict in useMethod"
                 />
               </el-select>
             </el-form-item>
           </el-col>
           <el-col :span="7">
             <el-form-item label="付数" prop="pairNum">
               <el-input v-model="herbalPrescription.pairNum" ></el-input>
             </el-form-item>
           </el-col>
         </el-row>
       <el-row>
         <el-col>
           <el-tag style="margin-right: 10px">项目金额总价:</el-tag>
           <el-tag type="danger">{{ totalMoney| rounding}} 元</el-tag>
         </el-col>
       </el-row>
       <el-table :data="drugInfoList">
         <el-table-column align="center" class-name="small-padding fixed-width" width="50px">
           <template slot-scope="scope">
             <el-button
               size="mini"
               type="text"
               @click="drugDelete(scope.$index,drugInfoList)"
             >删除</el-button>
           </template>
         </el-table-column>
         <el-table-column label="药品id" v-if="false" align="center" prop="drug.id" />
         <el-table-column label="药品名" align="center" prop="drug.name" />
         <el-table-column label="规格" align="center" prop="drug.format" />
         <el-table-column label="单价" align="center" prop="drug.price" width="60px"/>
         <el-table-column label="数量" align="center" prop="currentNum">
           <template slot-scope="scope">
             <el-input-number v-model="scope.row.currentNum" @change="totalPrice()" controls-position="right" size="small" style="width:90px" :min="1" :max="20"  />
           </template>
         </el-table-column>
         <el-table-column label="剂型" align="center" prop="drug.dosageName"/>
         <el-table-column label="医嘱" align="center" prop="medicalAdvice" >
           <template slot-scope="scope">
             <el-input v-model="scope.row.medicalAdvice" />
           </template>
         </el-table-column>
         <el-table-column label="脚注" align="center" prop="footnote" >
           <template slot-scope="scope">
             <el-input v-model="scope.row.footnote" />
           </template>
         </el-table-column>

       </el-table>
       </el-form>
     </el-main>
     </el-container>
    </el-dialog>
  </div>
</template>

<script>
  import {listHerbal_prescription_record,getHerbalModel,getModelItemByModelID,invalidToDataBase,addHerbal_prescription_record,updateHerbal_prescription_record,delHerbal_prescription_record,addHerbal_prescriptionToRedis,getPrescriptionName} from "@/api/dms/herbal_prescription_record";
  import { listDrug } from "@/api/dms/drug";
  import {listUsed} from "@/api/dms/used";

  export default {
    /** 接收父组件传参*/
    props: ["registrationId"],

    data() {
      const prescriptionName = (rule, value, callback) => {
        getPrescriptionName(value).then(response => {
          if(response.data===1){
            callback(new Error("处方名称不能重复"));
          }else{
            callback()
          }
        })

      }
      return {
        //模板详情
        modelInfo:{},
        //隐藏模板详情
        testModelShow:false,
        /**草药处方——数据表格*/
        tableData: [],
        /**总金额*/
        totalMoney: 0,
        /**药品总条数*/
        total: 0,
        /**常用药品数据*/
        frequentDrugList:null,
        /**药品数据表格*/
        drugList:null,
        /**是否显示只读*/
        showButton:false,
        /**处方详情*/
        herbalPrescription:{
          herbalItem:null
        },
        title:null,
        /**使用方法*/
        useMethod:[],
        /**使用频率*/
        useFrequency:[],
        /**右边草药详情数据*/
        drugInfoList:[],
        /** 模板显隐状态*/
        elIfShow:true,
        /**模版集合*/
        modelList: [],
        /**根据药品名称模糊查询 */
        drugName: undefined,
        /** 处方名称*/
        name:null,
        /**模板明细详情*/
        model_info: {},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          name: null,
          projectType:103
        },
        /**是否显示弹出层*/
        open: false,
        /**选中数组*/
        ids: [],
        /**选中的行数据*/
        operatedData:[],
        /** 禁用弹窗*/
        forbidden:false,
        /**非单个禁用*/
        single: true,
        /**非多个禁用*/
        multiple: true,
        //挂号级别
        formatStatus:
          {"-1": "未开立", "0": "作废", "1": "未缴费", "2": "已缴费", "3": "已发药", "4": "已退药", "5": "已退费", "6": "已过期"},

        // 表单校验
        rules: {
          name: [
            { required: true, message: "处方名称不能为空", trigger: "blur" }
            , {validator: prescriptionName,message:"处方名称不能重复",trigger:'blur'}
          ],

      medicalAdvice: [
            { required: true, message: "医嘱不能为空", trigger: "blur" }
          ],
          therapy: [
            { required: true, message: "治法不能为空", trigger: "blur" }
          ],
          usageMeans: [
            { required: true, message: "用法不能为空", trigger: "blur" }
          ],
          pairNum: [
            { required: true, message: "付数不能为空", trigger: "blur" },
            {
              pattern: /^\d$/,
              message: "付数必须为数字并且不能大于10",
              trigger: "blur"
            }
          ],

        },
      }


    },
    /** 过滤总价，只要小数点后两位*/
    filters: {
      rounding(value) {
        return value.toFixed(2);
      }
    },
    watch:{     //监听传值的变化，进行相应的操作即可
      registrationId: function(a,b){
        /** 查询患者的草药处方*/
        this.getHerbalPre();
      }
    },


    created() {
      /** 查询患者的草药处方*/
      this.getHerbalPre();
      /** 查询用户下所有草药模板 */
      this.getMedicineModelList();
      /** 查询常用草药 */
      this.getFrequentDrugList();
      /** 查询药品详情信息方法*/
      this.getDrugList();
      /** 药品用法*/
      this.getDicts("drug_use_method").then(response => {
        this.useMethod = response.data;
      });
    },

    methods: {
      /** 显示模板详情*/
      handleClick(row){
        this.testModelShow=true;
        this.modelInfo=row;
      },
      /**查询模版集合*/
      getMedicineModelList() {
        getHerbalModel().then(response => {
          this.modelList = response.data;
        });
      },
      /** 通过挂号Id查询草药处方 */
      getHerbalPre(){
        let registrationId={'registrationId':this.registrationId}
          listHerbal_prescription_record(registrationId).then(response => {
          this.tableData = response.rows;
        });
      },
      /** 查询常用草药 */
      getFrequentDrugList() {
        this.loading = true;
        listUsed(this.queryParams).then(response => {
          this.frequentDrugList = response.rows;
          this.loading = false;
        });
      },
      /** 药品行点击事件*/
      drugClick(row){
        for(let i = 0; i<this.drugInfoList.length;i++){
          if(this.drugInfoList[i].drug.id == row.id){
            this.drugInfoList[i].currentNum=this.drugInfoList[i].currentNum+1;
            this.totalPrice();//计算总金额
            return true;
          }
        }
        let drug={id:row.id,name:row.name,format:row.format,price:row.price,dosageName:row.dosageName};
        this.drugInfoList.push({currentNum:1,drug:drug});
        this.totalPrice();//计算总金额
      },
      /** 删除该行药品信息按钮操作 */
      drugDelete(index,row){
        row.splice(index,1);
        this.totalPrice();//计算总金额
      },
      /** 查询药品详情信息方法*/
      getDrugList(){
        this.queryParams.typeId = 103;
        listDrug(this.queryParams).then(response => {
          this.drugList = response.rows;
          this.total = response.total;
        });
      },
      /** 关闭弹框清除数据*/
      resetForm(){
        this.herbalPrescription={};
        this.getHerbalPre();
        this.totalMoney=0;
        this.drugInfoList=[];
        this.clearValidate('herbalPrescription') // 清除整个表单的校验
        this.open=false;
      },
      /** 提交按钮 */
      submitForm: function() {

        this.$refs["herbalPrescription"].validate(valid => {
          if (valid) {
            if (this.drugInfoList.length != 0) {
              this.addPrescription();
              if (this.herbalPrescription.id != undefined) {
                updateHerbal_prescription_record(this.herbalPrescription).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getHerbalPre();
                  }
                });
              } else {
                addHerbal_prescriptionToRedis(this.herbalPrescription).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getHerbalPre();
                  }
                });
              }
            }else{
              this.msgError("至少添加一条数据");
            }
          }
        });
      },
      //控制模板显示与隐藏
      showOrHidden() {
        this.elIfShow = !this.elIfShow;

      },

      /** 新增按钮操作 */
      drugTableOpenAndClose() {
        this.open = true;
        this.title = "添加处方";
        this.showButton=false;
      },
      /**通过药品名查询药品信息*/
      getDrugByName(){
        this.queryParams.name=this.drugName;
        this.getDrugList();
      },

      /**计算总价*/
      totalPrice(){
        this.totalMoney = 0;
        for(let i= 0;i<this.drugInfoList.length;i++){
          this.totalMoney += this.drugInfoList[i].drug.price*this.drugInfoList[i].currentNum;
        }
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const names=row.name||this.name;
        const data=this.operatedData;
        const this1=this;
        this.$confirm('是否确认删除处方名为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          for (let i = 0; i <data.length ; i++) {
            if(data[i].status!=-1){
              this1.msgError("只能删除未开立的处方");
              return false;
            }
          }
          delHerbal_prescription_record(names).then(response => {
            if (response.code === 200) {
              this1.msgSuccess("删除成功");
              this1.open = false;
              this1.getHerbalPre();
            }
          });
        });
      },
      /** 开立处方按钮操作 */
      handleAdd(row) {
        const names=row.name||this.name;
        const data=this.operatedData;
        const this1=this;
        this.$confirm('是否确认添加处方名为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          for (let i = 0; i <data.length ; i++) {
            if(data[i].status!=-1){
              this1.msgError("只能添加未开立的处方");
              return false;
            }
          }
          addHerbal_prescription_record(names).then(response => {
            if (response.code === 200) {
              this1.msgSuccess("添加成功");
              this1.open = false;
              this1.getHerbalPre();
            }
          });
        });
      },
      /** 作废处方按钮操作 */
      handleInvalid(row) {
        const names = row.name || this.name;
        const userIds = row.id || this.ids;
        const data=this.operatedData;
        const this1=this;
        this.$confirm('是否确认作废处方名为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          for (let i = 0; i <data.length ; i++) {
            if(data[i].status!=1){
              this1.msgError("只能作废未缴费的处方");
              return false;
            }
          }
          invalidToDataBase(userIds,0).then(response => {
            if (response.code === 200) {
              this1.msgSuccess("操作成功");
              this1.open = false;
              this1.getHerbalPre();
            }
          });
        });
      },
      /**编辑处方*/
      editPrescription(row){
        this.open = true;
        this.title = "编辑处方";
        this.showButton=false;
        this.herbalPrescription=row;
        this.herbalPrescription.id=0;
        this.drugInfoList=row.dmsHerbalItemRecord;
        this.totalPrice();
      },

      /**查看处方*/
      viewPrescription(row){
        this.open = true;
        this.title = "查看处方";
        this.showButton=true;
        this.herbalPrescription=row;
        this.drugInfoList=row.dmsHerbalItemRecord;
        this.totalMoney=this.herbalPrescription.amount;
      },
      /** 添加处方*/
      addPrescription(){
        this.herbalPrescription.amount=this.totalMoney;
        this.herbalPrescription.status=-1;
        this.herbalPrescription.registrationId=this.registrationId;
        this.herbalPrescription.dmsHerbalItemRecord=this.drugInfoList;
      },

      /**多选框选中数据*/
      handleSelectionChange(selection) {

        this.ids = selection.map(item => item.id);
        this.name = selection.map(item => item.name);
        this.operatedData = selection;
        this.single = selection.length!==1;
        this.multiple = !selection.length;
      },

      /**草药模板点击*/
      handleDblClick(row, event, column) {
        this.$confirm("确定要加入模板名为"+row.name+"的数据到新处方吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          getModelItemByModelID(row.id).then(response => {
            this.showButton=false;
            if(response.data!=null){
              this.herbalPrescription=response.data;
              this.drugInfoList=this.herbalPrescription.dmsHerbalItemRecord;
              this.totalPrice();
              this.open=true;
            }else{
              this.msgError("模板中没有数据");
            }


        });
        }).catch(function () {
          this.msgSuccess("出现异常");
        });

      },

    }
  }
</script>

<style scoped>
  #doWith i {
    width: 120px;
    font-size: 20px;
    text-align: center;
    line-height: revert;
    line-height: initial;
  }

  .menu > button {
    font-size: 12px;
    color: #409EFF;
    padding-right: 22px;
  }
  .dialog{
    left: -30%;
  }
  .head>button{
    margin-left: 30px;
  }
  .head {
    height: 50px;
    width: 750px;
    line-height: 50px;
    margin-left: -15px;
  }
  #container{
    padding-top:1px;
  }
  .btn_right{
    float: right;
    margin-top: 5px
  }
</style>
